package com.zhangchuchu.neohealth.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangchuchu.neohealth.common.R;
import com.zhangchuchu.neohealth.entity.Community;
import com.zhangchuchu.neohealth.entity.DTO.CommunityDTO;
import com.zhangchuchu.neohealth.service.CommunityService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Community)表控制层
 *
 * @author makejava
 * @since 2025-03-29 20:51:17
 */
@RestController
@RequestMapping("/community")
public class CommunityController {
    /**
     * 服务对象
     */
    @Resource
    private CommunityService communityService;

    private static final String UPLOAD_DIR = "D:\\IdeaProjects\\neo-health\\src\\main\\resources\\static\\img";


    /**
     * 条件查询
     */
    @GetMapping("/searchList")
    public R<Page<Community>> selectList(@RequestParam(value = "query", required = false) String query,@RequestParam int page, @RequestParam int size) {
        Page<Community> page1 = new Page<>(page,size);
        QueryWrapper<Community> queryWrapper = new QueryWrapper<>();

        // 如果查询条件存在，则加入查询条件
        if (query != null && !query.trim().isEmpty()) {
            queryWrapper.like("title", query)  // 假设根据标题进行模糊查询
                    .or().like("content", query);  // 也可以根据内容进行模糊查询
        }
        return R.success(communityService.page(page1,queryWrapper));
    }
    /**
     * 查询所有数据（不分页）
     *
     * @return 所有数据
     */
    @GetMapping("/getList")
    public R<List<CommunityDTO>> selectList() {
        List<CommunityDTO> list = communityService.getCommunity(); // 查询所有数据
        return R.success(list);
    }

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param community 查询实体
     * @return 所有数据
     */
    @GetMapping()
    public R selectAll(@RequestParam int page, @RequestParam int size, Community community) {
        Page<Community> pageObj = new Page<>(page, size);
        return R.success(this.communityService.page(pageObj, new QueryWrapper<>(community)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return R.success(this.communityService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param community 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody Community community) {
        return R.success(this.communityService.save(community));
    }

    /**
     * 修改数据
     *
     * @param community 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody Community community) {
        return R.success(this.communityService.updateById(community));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public R delete(@RequestParam("idList") List<Long> idList) {
        return R.success(this.communityService.removeByIds(idList));
    }

    @GetMapping("/details")
    public R<List<CommunityDTO>> getCommunityDetails(@RequestParam Long commentId, @RequestParam Long userId) {
        return R.success(communityService.getCommunityWithUserAndComment(commentId, userId));
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> uploadFile(@RequestParam("file") MultipartFile file) {
        Map<String, String> result = new HashMap<>();

        if (file.isEmpty()) {
            result.put("error", "No file uploaded");
            return result;
        }

        try {
            // 获取文件名并设置目标路径
            String originalFilename = file.getOriginalFilename();
            String filePath = UPLOAD_DIR + "/" + originalFilename;
            File dest = new File(filePath);

            // 创建父目录
            dest.getParentFile().mkdirs();
            file.transferTo(dest); // 保存文件

            // 返回文件路径
            result.put("path", "/img/" + dest.getName()); // 返回相对路径
        } catch (IOException e) {
            result.put("error", "File upload failed");
            e.printStackTrace();
        }

        return result;
    }
}

